package com.atung.merchant.tool;

import cn.hutool.jwt.JWTUtil;
import com.atung.merchant.exception.VerifyIdentityExcetion;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Component
public class VerifyToken {

    public static Boolean verifyApiFilter(HttpServletRequest httpRequest) {
        String headerToken = httpRequest.getHeader("X-Farm-Token");
        String jwtIp = JWTUtil.parseToken(headerToken).getPayload().getClaim("visaIp").toString();
        String senIp = IPUtil.getIpaddressPublicNetWork();
        if (!Objects.equals(jwtIp, senIp)) {
            return false;
        }
        return true;
    }

    public static TokenUserDO verifyToken(HttpServletRequest httpRequest) throws VerifyIdentityExcetion {
        String headerToken = httpRequest.getHeader("X-Farm-Token");
        Object data = JWTUtil.parseToken(headerToken).getPayload("data");
        String jwtIp = JWTUtil.parseToken(headerToken).getPayload().getClaim("visaIp").toString();
        String senIp = IPUtil.getIpaddressPublicNetWork();
        if (!Objects.equals(jwtIp, senIp)) {
            throw new VerifyIdentityExcetion("已启动IP过滤");
        }
        if (Objects.nonNull(data)) {
            TokenUserDO tokenUserDO = new TokenUserDO();
            tokenUserDO.setUserId(Long.valueOf(data.toString()));
            return tokenUserDO;
        }
        throw new VerifyIdentityExcetion("登录失败");
    }
}
